# -*- coding: utf-8 -*-
# @Time: 2025/7/24 7:52
# @Author: foxhuty
# @File: crawling_B_1.py
import requests
from bs4 import BeautifulSoup
import re

# 代理信息
proxyHost = "www.16yun.cn"
proxyPort = "5445"
proxyUser = "16QMSOML"
proxyPass = "280651"

# 设置代理
proxies = {
    "http": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}",
    "https": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}"
}

# 视频页面的URL
video_page_url = "https://www.bilibili.com/video/BV1ZQVtztE2G/?spm_id_from=333.337.search-card.all.click&vd_source=416c516993c044dbe2bb6e5b56753a8a"  # 替换为实际的视频页面URL

# 发送GET请求获取页面内容
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36"
}

try:
    response = requests.get(video_page_url, headers=headers, proxies=proxies, timeout=10)

    if response.status_code == 200:
        html_content = response.text
        print("页面内容获取成功！")
    else:
        print(f"页面内容获取失败，状态码：{response.status_code}")
        exit()
except requests.exceptions.RequestException as e:
    print(f"请求失败：{e}")
    print("可能的原因包括网络问题、代理服务器不可用或目标网页无法访问。")
    print("请检查网页链接的合法性，并尝试重新运行脚本。")
    exit()

# 解析HTML内容
soup = BeautifulSoup(html_content, "html.parser")

# 使用正则表达式提取视频地址
script_tags = soup.find_all("script")
video_url_pattern = re.compile(r'"url":"(.*?\.mp4)"')

video_url = None
for script in script_tags:
    match = video_url_pattern.search(script.string)
    if match:
        video_url = match.group(1)
        break

if video_url:
    print("视频地址提取成功：", video_url)
else:
    print("未找到视频地址")
    exit()

# 下载视频文件
def download_video(url, filename):
    try:
        response = requests.get(url, headers=headers, proxies=proxies, stream=True, timeout=10)
        if response.status_code == 200:
            with open(filename, "wb") as f:
                for chunk in response.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
            print(f"视频下载完成，保存为：{filename}")
        else:
            print(f"视频下载失败，状态码：{response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"下载失败：{e}")
        print("请检查视频链接的合法性，并尝试重新运行脚本。")

# 调用下载函数
download_video(video_url, "video.mp4")


